package com.ruoyi.client.schedule;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.client.domain.entity.BlogArticle;
import com.ruoyi.client.domain.entity.BlogCollect;
import com.ruoyi.client.domain.entity.BlogLike;
import com.ruoyi.client.mapper.BlogCollectMapper;
import com.ruoyi.client.service.IBlogArticleService;
import com.ruoyi.client.service.IBlogCollectService;
import com.ruoyi.client.service.IBlogLikeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Configuration
public class ArticleScheduled {
    @Autowired
    IBlogCollectService collectService;
    @Autowired
    BlogCollectMapper collectMapper;
    @Autowired
    IBlogLikeService likeService;
    @Autowired
    IBlogArticleService articleService;

    /**
     * 每天晚上11点55执行
     * 计算点赞数、收藏数、浏览量、评论数
     */
    @Scheduled(cron = "0 55 23 * * ?") // 11点55 ：0 55 23 * * ?  每分钟：0 * * * * ?
    public void autoComputeLikeAndCollectAndWatchByDay(){
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime startOfDay = now.with(LocalTime.MIN); // 今天的开始时间（00:00:00）
        LocalDateTime endOfDay = now.with(LocalTime.MAX);   // 今天的结束时间（23:59:59.999999999）

        List<BlogCollect> collectList = collectService.list(Wrappers.<BlogCollect>lambdaQuery()
            .between(BlogCollect::getCreateTime, startOfDay, endOfDay)
        );

        List<BlogLike> likeList = likeService.list(Wrappers.<BlogLike>lambdaQuery()
            .between(BlogLike::getCreateTime, startOfDay, endOfDay)
        );
        Map<Object, Integer> collectMap = computeCollectNum(collectList);
        Map<Object, Integer> likeMap = computeLikeNum(likeList);
        // 更新浏览量 todo
        // 更新评论数
        // 更新文章收藏数
        if (CollectionUtil.isNotEmpty(collectMap)) {
            for (Map.Entry<Object, Integer> entry : collectMap.entrySet()) {
                UpdateWrapper<BlogArticle> collectUpdateWrapper = new UpdateWrapper<>();

                collectUpdateWrapper
                    .setSql("collect_num = collect_num + " + entry.getValue())
                    .eq("id", entry.getKey());
                articleService.update(collectUpdateWrapper);
            }
        }
        // 更新点赞数
        if (CollectionUtil.isNotEmpty(likeMap)) {
            for (Map.Entry<Object, Integer> entry : likeMap.entrySet()) {
                UpdateWrapper<BlogArticle> likeUpdateWrapper = new UpdateWrapper<>();
                likeUpdateWrapper
                    .setSql("like_num = like_num + " + entry.getValue())
                        .eq("id", entry.getKey());
                articleService.update(likeUpdateWrapper);
            }
        }
    }
    private Map<Object,Integer> computeLikeNum(List<BlogLike> likeList) {
        HashMap<Object, Integer> likeMap = new HashMap<>();
        likeList.stream().forEach(v -> {
            Integer integer = likeMap.get(v.getTargetId());
            if (integer == null) {
                likeMap.put(v.getTargetId(),1);
            }
            else {
                likeMap.put(v.getTargetId(), integer + 1);
            }
        });
        return likeMap;
    }

    private Map<Object,Integer> computeCollectNum(List<BlogCollect> collectList) {
        HashMap<Object, Integer> collectMap = new HashMap<>();
        collectList.stream().forEach(v -> {
            Integer integer = collectMap.get(v.getTargetId());
            if (integer == null) {
                collectMap.put(v.getTargetId(),1);
            }
            else {
                collectMap.put(v.getTargetId(), integer + 1);
            }
        });
        return collectMap;
    }
}
